<?php
//Root pot do mape, naj bi delovalo tudi $_SERVEr['DOCUMENT_ROOT'] pa ne tako kot bi moralo, spremeni za pravilno navigacijo po meniju prodajalca in admina
$root = "http://localhost/EP_Trgovina/";
$rootLog = "/var/www/EP_Trgovina/log.txt";
//Vključimo datoteko za pisanje v bazo in razred za pisanje v Dnevnik
include "DAO.php";
include "Dnevnik.php";
function showEditCustomers() {
    $result = dbGetResult("SELECT * FROM Customers");
    echo "<h2>Edit customers</h2>";
    $headTable = "<thead><tr><td>Name</td><td>Surname</td><td>E-mail</td><td>Address</td><td>City</td><td>Post</td><td>Phone</td><td>Password</td><td>Activated</td></thead>";
    echo "<table>";
    echo $headTable;
    while ($row = mysql_fetch_assoc($result)) {
        $id = $row["ID"];
        $ime = $row['Ime'];
        $priimek = $row['Priimek'];
        $mail = $row['Email'];
        $naslov = $row['Naslov'];
        $mesto = $row['Mesto'];
        $posta = $row['Posta'];
        $tel = $row['Tel'];
        $aktiviran = $row['Aktiviran'];
        $aktiv = "";
        $pass = $row['Geslo'];
        if ($aktiviran == 1)
            $aktiv = "checked='checked'";
        echo "<tr><form action='#' method='post'><td><input size='8' type=text name='ime' value='$ime' /></td><td><input size='8' type=text name='priimek' value='$priimek' /></td>
            <td><input size='20' type=text name='mail' value='$mail' /></td><td><input size='10' type=text name='naslov' value='$naslov' /></td>
                <td><input size='8' type=text name='mesto' value='$mesto' /></td><td><input size='3' type=text name='posta' value='$posta' /></td>
                    <td><input size='9' type=text name='tel' value='$tel' /></td><td><input size='6' type=password name='geslo' value='$pass' /></td>
                        <td><input type='checkbox' value='1' name='cb' " . $aktiv . " /><input type=hidden value='$id' name='id' /></td><td><input type='submit' value='Edit' /></td></form></tr>";
    }
    echo "<tr><td colspan='0'><h2>Add new customer</h2></td></tr>";
    echo "<tr><form action='#' method='post'><td><input size='8' type=text name='ime' /></td><td><input size='8' type=text name='priimek' /></td>
            <td><input size='20' type=text name='mail'  /></td><td><input size='10' type=text name='naslov' /></td>
                <td><input size='8' type=text name='mesto' /></td><td><input size='3' type=text name='posta' /></td>
                    <td><input size='9' type=text name='tel' /></td><td><input size='6' type=password name='geslo' /></td>
                    <td><input type='checkbox' name='cb' value='1' /><input type=hidden value='new' name='new' /></td><td><input type='submit' value='Add' /></td></form></tr>";

    echo "</table>";
}

function showEditSellers() {
    //Pridobimo vse prodajalce
    $result = dbGetResult("SELECT * FROM PowerUsers WHERE Admin=0");
    $headTable = "<thead><tr><td>Name</td><td>Surname</td><td>User identity</td><td>Password</td><td>Activated</td></thead>";
    echo "<h2>Edit sellers</h2>";
    echo "<table>";
    echo $headTable;
    while ($row = mysql_fetch_assoc($result)) {
        $id = $row["ID"];
        $ime = $row['Ime'];
        $priimek = $row['Priimek'];
        $emso = $row['EMSO'];
        $aktiviran = $row['Aktiviran'];
        $aktiv = "";
        $pass = $row['Geslo'];
        if ($aktiviran == 1)
            $aktiv = "checked='checked'";

        echo "<tr><form action='#' method='post'><td><input size='8' type=text name='ime' value='$ime' /></td><td><input size='8' type=text name='priimek' value='$priimek' /></td>
            <td><input size='20' type=text name='emso' value='$emso' /></td><td><input size='6' type=password name='geslo' value='$pass' /></td>
                        <td><input type='checkbox' value='1' name='cb' " . $aktiv . " /><input type=hidden value='$id' name='id' /></td><td><input type='submit' value='Edit' /></td></form></tr>";
    }
    echo "<tr><td colspan='0'><h2>Add new seller</h2></td></tr>";
    echo "<tr><form action='#' method='post'><td><input size='8' type=text name='ime' /></td><td><input size='8' type=text name='priimek' /></td>
            <td><input size='20' type=text name='emso' /></td><td><input size='6' type=password name='geslo' /></td>
                        <td><input type='checkbox' value='1' name='cb' /><input type=hidden value='new' name='new' /></td><td><input type='submit' value='New' /></td></form></tr>";

    echo "</table>";
}

function editCustomer() {
    global $rootLog;
    //ocistimo parametre proti sql inj
    $ime = dbCleanParameter($_POST['ime']);
    $priimek = dbCleanParameter($_POST['priimek']);
    $mail = dbCleanParameter($_POST['mail']);
    $naslov = dbCleanParameter($_POST['naslov']);
    $mesto = dbCleanParameter($_POST['mesto']);
    $posta = dbCleanParameter($_POST['posta']);
    $tel = dbCleanParameter($_POST['tel']);
    $pass = dbCleanParameter($_POST['geslo']); 
    
    if(isset($_SESSION['seller']))
            $user=$_SESSION['seller'];
    else  $user=$_SESSION['admin'];
    $user=  getNamePowerUser($user);
    
    //prevert mormo ce je pass ze hashed z md5 - a je tak pass v bazi
    $q = "SELECT COUNT(*) FROM Customers WHERE Geslo = '$pass'";
    $r = dbGetResult($q);
    $temp = mysql_fetch_assoc($r);
    $num = $temp['COUNT(*)'];
    
    if ($num == 0){
        //pass še ni hashed
        $passmd5 = md5($pass);
    }
    else{
        $passmd5 = $pass;
    }
    
    $log=new Dnevnik();
    $log->lfile($rootLog);
    
    if (isset($_POST["id"]))
        $id = $_POST["id"];

    if (isset($_POST['cb']) && $_POST['cb'] == 1)
        $aktiv = 1;
    else
        $aktiv = 0;
    
    if (strlen($ime) == 0 || strlen($priimek) == 0 || strlen($mail) == 0 || strlen($naslov) == 0 || strlen($mesto) == 0 || strlen($posta) == 0 || strlen($tel) == 0 || strlen($pass) == 0) {
        echo "<h3 style='color:red;'>All fields when editing or adding new user are required.</h3>";
        echo "<script>alert('Unsuccessful editing/adding user: " . $ime . "');</script></h3>";
    } else if (isset($_POST["new"])) {
        $query = "INSERT INTO Customers (Ime, Priimek, Email, Naslov, Mesto, Posta, Tel, Geslo, Aktiviran) VALUES ('$ime', '$priimek', '$mail', '$naslov', '$mesto', '$posta', '$tel', '$passmd5', '$aktiv')";
        dbGetResult($query);
        $log ->lwrite("[$user] Custumer inserted $ime $priimek");
    } else {
        echo "<h3 style='color:green;'>Successfully edited: " . $ime . " " . $priimek . "</h3>";
        $query = "UPDATE Customers SET Ime='$ime', Priimek='$priimek', Email='$mail', Naslov='$naslov', Mesto='$mesto', Posta='$posta', Tel='$tel', Geslo='$passmd5', Aktiviran='$aktiv' WHERE ID='$id'";
        dbGetResult($query);
        $log ->lwrite("[$user] Custumer edited $ime $priimek with id=$id");
    }
    $log->lclose();
}

function showEditArticles() {
    $result = dbGetResult("SELECT * FROM Artikel");
    echo "<h2>Edit articles</h2>";
    $headTable = "<thead><tr><td>Id</td><td>Artist</td><td>Album</td><td>Type</td><td>Description</td><td>Price</td><td>Image</td><td>Media</td><td>Qt</td></thead>";
    echo "<table>";
    echo $headTable;
    while ($row = mysql_fetch_assoc($result)) {
        $id = $row["id"];
        $izvajalec = $row['izvajalec'];
        $album = $row['album'];
        $zvrst = $row['zvrst'];
        $opis = $row['opis'];
        $cena = $row['cena'];
        $slika = $row['slika'];
        $media = $row['media'];
        $qt = $row['zaloga'];
        $aktiviran = $row['Aktiviran'];
        $aktiv = "";
        if ($aktiviran == 1)
            $aktiv = "checked='checked'";
        echo "<tr><form action='#' method='post'><td>$id</td><td><input size='8' type=text name='izvajalec' value='$izvajalec' /></td>
            <td><input size='20' type=text name='album' value='$album' /></td><td><input size='6' type=text name='zvrst' value='$zvrst' /></td>
                <td><input size='8' type=text name='opis' value='$opis' /></td><td><input size='3' type=text name='cena' value='$cena' /></td>
                    <td><input size='9' type=text name='slika' value='$slika' /></td><td><input size='1' type='text' name='media' value='$media' /></td>
                        <td><input type=\"number\" size='1' value='$qt' name='zaloga' /></td>
                            <td><input type='checkbox' value='1' name='cb' " . $aktiv . " /><input type=hidden value='$id' name='id' /></td><td><input type='submit' value='Edit' /></td>
                            <td><input type='submit' name='Remove' value='Remove' /></td></form></tr>";
    }
    echo "<tr><td colspan='0'><h2>Add new article</h2></td></tr>";
    echo "<tr><form action='#' method='post'><td></td><td><input size='8' type=text name='izvajalec'/></td>
            <td><input size='20' type=text name='album' /></td><td><input size='6' type=text name='zvrst'  /></td>
            <td><input size='8' type=text name='opis' /></td><td><input size='3' type=text name='cena' /></td>
                <td><input size='9' type=text name='slika' /></td><td><input size='1' type=text name='media' /></td>
                    <td><input size='1' type=\"number\" name='zaloga' /></td>
                    <td><input type='checkbox' value='1' name='cb' />
                    <input type=hidden value='new' name='new' /></td><td><input type='submit' value='Add' /></td></form></tr>";

    echo "</table>";
}

function editArticle() {
    global $rootLog;
    $user=  getNamePowerUser($_SESSION['seller']);
    
    $izvajalec = dbCleanParameter($_POST['izvajalec']);
    $album = dbCleanParameter($_POST['album']);
    $zvrst = dbCleanParameter($_POST['zvrst']);
    $opis = dbCleanParameter($_POST['opis']);
    $cena = dbCleanParameter($_POST['cena']);
    $slika = dbCleanParameter($_POST['slika']);
    $media = dbCleanParameter($_POST['media']);
    $zaloga = dbCleanParameter($_POST['zaloga']);
    if (isset($_POST["id"]))
        $id = $_POST["id"];
    
    if (isset($_POST['cb']) && $_POST['cb'] == 1)
        $aktiv = 1;
    else
        $aktiv = 0;

    $log=new Dnevnik();
    $log->lfile($rootLog);
    if (strlen($izvajalec) == 0 || strlen($album) == 0 || strlen($media) == 0 || strlen($zvrst) == 0 || strlen($opis) == 0 || strlen($cena) == 0 || strlen($slika) == 0 || strlen($zaloga) == 0 || strlen($aktiv) == 0) {
        echo "<h3 style='color:red;'>All fields are required when editing or adding new articles.</h3>";
        echo "<script>alert('Unsuccessful editing/adding article: " . $album . "');</script></h3>";
    } else if (isset($_POST["new"])) {
        echo "<script>alert('successful adding article: " . $album . "');</script>";
        $query = "INSERT INTO Artikel (izvajalec, album, zvrst, opis, cena, slika, media, zaloga, Aktiviran) VALUES ('$izvajalec', '$album', '$zvrst', '$opis', '$cena', '$slika', '$media', '$zaloga', '$aktiv')";
        dbGetResult($query);
        $log->lwrite("[$user] Inserted new article, aulbum=$album and gender=$zvrst");
    } else if (isset($_POST['Remove'])) {
        $query = "DELETE FROM Artikel WHERE id = $id";
        dbGetResult($query);
        $log->lwrite("[$user] Article with id=$id removed, author=$album and gender=$zvrst");
        echo "<script>alert('Article: " . $album . " removed successfully.');</script>";
    } else {
        echo "<h3 style='color:green;'>Successfully edited: " . $izvajalec . " " . $album . "</h3>";
        $query = "UPDATE Artikel SET izvajalec='$izvajalec', album='$album', zvrst='$zvrst', opis='$opis', cena='$cena', slika='$slika', media='$media', zaloga='$zaloga', Aktiviran='$aktiv' WHERE id='$id'";
        $log->lwrite("[$user] Edited article with id=$id, author=$album and gender=$zvrst");
        dbGetResult($query);
    }
    $log->lclose();
}

function editSeller() {
    global $rootLog;
    
    $ime = dbCleanParameter($_POST['ime']);
    $priimek = dbCleanParameter($_POST['priimek']);
    $emso = dbCleanParameter($_POST['emso']);
    $pass = dbCleanParameter($_POST['geslo']);
    
    $log=new Dnevnik();
    $log->lfile($rootLog);
    
    //prevert mormo ce je pass ze hashed z md5 - a je tak pass v bazi
    $q = "SELECT COUNT(*) FROM PowerUsers WHERE Geslo = '$pass' and Admin = 0";
    $r = dbGetResult($q);
    $temp = mysql_fetch_assoc($r);
    $num = $temp['COUNT(*)'];
    
    if ($num == 0){
        //pass še ni hashed
        $passmd5 = md5($pass);
    }
    else{
        $passmd5 = $pass;
    }
    
    if (isset($_POST["id"]))
        $id = $_POST["id"];

    $user =  getNamePowerUser($_SESSION['admin']);
    
    if (isset($_POST['cb']) && $_POST['cb'] == 1)
        $aktiv = 1;
    else
        $aktiv = 0;

    if (strlen($ime) == 0 || strlen($priimek) == 0 || strlen($emso) == 0 || strlen($pass) == 0) {
        echo "<h3 style='color:red;'>All fields when editing or adding new user are required.</h3>";
        echo "<script>alert('Unsuccessful editing/adding user: " . $ime . "');</script></h3>";
    } else if (isset($_POST["new"])) {
        $query = "INSERT INTO PowerUsers (Ime, Priimek, EMSO, Geslo, Aktiviran) VALUES ('$ime', '$priimek', '$emso', '$passmd5', '$aktiv')";
        dbGetResult($query);
        $log ->lwrite("Dodan nov prodajalec $ime $priimek");
        
    } else {
        echo "<h3 style='color:green;'>Successfully edited: " . $ime . " " . $priimek . "</h3>";
        $query = "UPDATE PowerUsers SET Ime='$ime', Priimek='$priimek', EMSO='$emso', Geslo='$passmd5', Aktiviran='$aktiv' WHERE ID='$id'";
        dbGetResult($query);
        $log ->lwrite("[$user] Posodobljen prodajalec $ime $priimek z id=$id:");
    }
    $log->lclose();
}

function getNamePowerUser($id) {
    $id = dbCleanParameter($id);
    $query = "SELECT * FROM PowerUsers WHERE ID='$id'";
    $result = dbGetResult($query);
    $row = mysql_fetch_assoc($result);
    
    return $row['Ime'] . " " . $row['Priimek'];
}

function printArtikelResult($result) {  //funkcija, ki izpise artikle na, pridobljene iz baze, na stran.
    $counterOut = 0;
    while ($row = mysql_fetch_assoc($result)) {

        $id = $row['id'];
        $artist = $row['izvajalec'];
        $album = $row['album'];
        $description = $row['opis'];
        $price = $row['cena'];
        $image = $row['slika'];
        if (isset($_GET["type"]))
            $tp = dbCleanParameter($_GET["type"]);
        else
            $tp = "everything";

        if ($counterOut % 2 != 0) {
            print ("<div class=\"cnt\"><div class=\"product\"><img src=\"$image\" class=\"productpic\" alt=\"$artist\" />" .
                    "<div class=\"description\">" .
                    "<h4>$artist</h4><br/>" .
                    "<h5>$album</h5><br/>" .
                    "<p>$description</p>" .
                    "<h3>$$price</h3><a href=\"#\"><div class=\"ply\"><img src=\"play2.png\" class=\"playit2\" alt=\"play\" /></div></a>" .
                    "<a href=\"./index.php?call=cart&id=$id&type=$tp\"><div class=\"ply\"><img src=\"buyitnovo.jpg\" class=\"buyit\" alt=\"buy it\" /></div></a>" .
                    "</div></div></div>");
        } else {
            print ("<div class=\"cnt\"><div class=\"product2\"><img src=\"$image\" class=\"productpic\" alt=\"$artist\" />" .
                    "<div class=\"description\">" .
                    "<h4>$artist</h4><br/>" .
                    "<h5>$album</h5><br/>" .
                    "<p>$description</p>" .
                    "<h3>$$price</h3><a href=\"#\"><div class=\"ply\"><img src=\"play1.png\" class=\"playit1\" alt=\"play\" /></div></a>" .
                    "<a href=\"./index.php?call=cart&id=$id&type=$tp\"><div class=\"ply\"><img src=\"buyitnovo.jpg\" class=\"buyit\" alt=\"buy it\" /></div></a>" .
                    "</div></div></div>");
        }
        $counterOut += 1;
    }
}

function register() {   //funkcija za registracijo stranke
    if (isset($_POST["loginEmail"]) and isset($_POST["loginFirstname"]) and
            isset($_POST["loginLastname"]) and isset($_POST["loginAddress"]) and
            isset($_POST["loginCity"]) and isset($_POST["loginPost"]) and isset($_POST["loginNum"]) and
            isset($_POST["loginPassword"]) and isset($_POST["loginConfirmpassword"]))
        if (dbCleanParameter ($_POST["loginEmail"]) != "" and dbCleanParameter ($_POST["loginFirstname"]) != ""
                and dbCleanParameter ($_POST["loginLastname"]) != "" and dbCleanParameter ($_POST["loginAddress"]) != "" and
                dbCleanParameter ($_POST["loginCity"]) != "" and $_POST["loginPost"] != "" and $_POST["loginNum"] != ""
                and dbCleanParameter ($_POST["loginPassword"]) != "" and dbCleanParameter ($_POST["loginConfirmpassword"]) != "") {
                //CAPTCHA!!
                $privatekey = "6LdmK9sSAAAAAHaVgw88fxiQSjBD4eZJ_E0wSZvf";
                $verify = recaptcha_check_answer($privatekey, $_SERVER['REMOTE_ADDR'], dbCleanParameter ($_POST['recaptcha_challenge_field']), dbCleanParameter ($_POST['recaptcha_response_field']));
                if (!$verify->is_valid) {
                    echo "<script>";
                    echo "alert('Wrong captcha input');";
                    echo "</script>";
                } else {

                $name = dbCleanParameter($_POST["loginFirstname"]);
                $lname = dbCleanParameter($_POST["loginLastname"]);
                $addr = dbCleanParameter($_POST["loginAddress"]);
                $city = dbCleanParameter($_POST["loginCity"]);
                $post = dbCleanParameter($_POST["loginPost"]);
                $num = dbCleanParameter($_POST["loginNum"]);
                $regpass1 = dbCleanParameter($_POST["loginPassword"]);
                $regpass2 = dbCleanParameter($_POST["loginConfirmpassword"]);
                $mail = dbCleanParameter($_POST["loginEmail"]);

                if (preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $mail)
                        and $regpass1 == $regpass2 and strlen($regpass1) > 3) { // velja, ce ustreza email in sta gesli enaki
                    $boolGo = false;
                    $boolMailUname = true;
                    $regPassmd5 = md5($regpass1);
                    echo $regPassmd5;
                    $query = "INSERT INTO Customers (Ime, Priimek, Email, Naslov, Mesto, Posta, Tel, Geslo)" .
                            " VALUES ('$name', '$lname', '$mail','$addr', '$city', '$post', '$num', '$regPassmd5')";
                    $queryBool = "SELECT * FROM Customers WHERE Email = '$mail'";
                    $rs = dbGetResult($queryBool);

                    while ($row = mysql_fetch_assoc($rs)) { //preveri, ce ni kdo s takimi podatki ze vpisan
                        $boolMailUname = false;
                    }

                    if ($boolMailUname) {
                        $boolGo = true;
                        if (!( $result = dbGetResult($query) )) {
                            print( "<p>Could not execute query!</p>");
                            die(mysql_error() . "</body></html>");
                        } else {
                            $querySeja = "SELECT ID FROM Customers WHERE Email = '$mail'";
                            $resultUporabnik = dbGetResult($querySeja);
                            $uporabnikSeja = mysql_fetch_assoc($resultUporabnik);
                            //$_SESSION['uporabnik'] = $uporabnikSeja['ID'];
                            
                            posljiPotrditveniMail($mail,$uporabnikSeja['ID']);
                            
                            echo "<script>location.href='prijava.php'</script>";
                            //header("Location: ./index.php");
                            return;
                        }
                    } else {
                        if (isset($_COOKIE["language"])) {
                            if ($_COOKIE["language"] == "slo") {
                                echo "<script>";
                                echo "alert('Uporabnisko ime in/ali e-mail naslov ze zasedena.');";
                                echo "</script>";
                            } else {
                                echo "<script>";
                                echo "alert('Username and/or e-mail address already taken.');";
                                echo "</script>";
                            }
                        } else {
                            echo "<script>";
                            echo "alert('Username and/or e-mail address already taken.');";
                            echo "</script>";
                        }
                        return -1;
                    }
                }
                else{
                    
                    echo "<script>";
                    echo "alert('Insert valid email address, your password must contain more than 3 characters.');";
                    echo "</script>";
                }
            }
        }
}

function changePasswordU() {

    if (isset($_POST["oldPassU"]) and isset($_POST["newPassU"]) and isset($_POST["newPassConfU"])) {

        if ($_POST["oldPassU"] != "" and $_POST["newPassU"] != "" and $_POST["newPassConfU"] != "") {

            $oPass = $_POST["oldPassU"];
            $nPass = $_POST["newPassU"];
            $nPassC = $_POST["newPassConfU"];

            $custID = dbCleanParameter($_SESSION['uporabnik']);

            //iz baze poberemo trenutni password uporabnika
            $getPassQuery = "SELECT Geslo FROM Customers WHERE ID = '$custID'";
            $rs = dbGetResult($getPassQuery);
            $resPass = mysql_fetch_assoc($rs);
            $DBPass = $resPass['Geslo'];        //md5 pass


            //ce je old pass OK in ce sta nova enaka
            if (md5($oPass) == $DBPass and $nPass == $nPassC) {
                $nPassmd5 = md5($nPass);  //damo nov pass v md5
                //v bazi zamenjamo star password z novim v md5
                $chQuery = "UPDATE Customers SET Geslo = '$nPassmd5' WHERE ID = '$custID'";
                $res = dbGetResult($chQuery);
                if (!$res) {
                    print( "<p>Could not execute query!</p>");
                    die(mysql_error());
                } else {
                    //ce je geslo uspesno zamenjamo gremo nazaj na my account
                    header("Location: ./index.php");
                }
            } else {
                //povemo da nemoremo zamenjati gesla
                echo "<script>";
                echo "alert('Could not change password.');";
                echo "</script>";
            }
        }
    }
}

function changePasswordA() {

    if (isset($_POST["oldPassA"]) and isset($_POST["newPassA"]) and isset($_POST["newPassConfA"])) {

        if ($_POST["oldPassA"] != "" and $_POST["newPassA"] != "" and $_POST["newPassConfA"] != "") {

            $oPass = $_POST["oldPassA"];
            $nPass = $_POST["newPassA"];
            $nPassC = $_POST["newPassConfA"];

            $usrID = dbCleanParameter($_SESSION['admin']);

            //iz baze poberemo trenutni password admina
            $getPassQuery = "SELECT Geslo FROM PowerUsers WHERE ID = '$usrID'";
            $rs = dbGetResult($getPassQuery);
            $resPass = mysql_fetch_assoc($rs);
            $DBPass = $resPass['Geslo'];

            //ce je old pass OK in ce sta nova enaka
            if ($oPass == $DBPass and $nPass == $nPassC) {
                //v bazi zamenjamo star password z novim
                $chQuery = "UPDATE PowerUsers SET Geslo = '$nPass' WHERE ID = '$usrID'";
                $res = dbGetResult($chQuery);
                if (!$res) {
                    print( "<p>Could not execute query!</p>");
                    die(mysql_error());
                } else {
                    //ce je geslo uspesno zamenjamo gremo nazaj na my account in povemo da smo zamenjali geslo
                    echo "<script>";
                    echo "alert('Succesfully changed password.');";
                    echo "</script>";
                    header("Location: ./adminSite.php");
                }
            } else {
                //povemo da nemoremo zamenjati gesla
                echo "<script>";
                echo "alert('Could not change password.');";
                echo "</script>";
            }
        }
    }
}
function posljiPotrditveniMail($to, $id){
    global $root;
    $subject="Submit your registration on PodutikRecords";
    $message="If you didn't register on web store Podutik Records please ignore this email.
        Otherwise, click on the link below and start actively using our web store.
        
        URL: $root/activateCustomer.php?usr=$id
            
        Your PodutikRecords admin team";
    $headers="Form: info@podutikrecords.com";
    mail($to,$subject,$message,null,$headers);
    
}
function changePasswordS() {

    if (isset($_POST["oldPassS"]) and isset($_POST["newPassS"]) and isset($_POST["newPassConfS"])) {

        if ($_POST["oldPassS"] != "" and $_POST["newPassS"] != "" and $_POST["newPassConfS"] != "") {

            $oPass = $_POST["oldPassS"];
            $nPass = $_POST["newPassS"];
            $nPassC = $_POST["newPassConfS"];

            $usrID = dbCleanParameter($_SESSION['seller']);

            //iz baze poberemo trenutni password admina - v md5
            $getPassQuery = "SELECT Geslo FROM PowerUsers WHERE ID = '$usrID'";
            $rs = dbGetResult($getPassQuery);
            $resPass = mysql_fetch_assoc($rs);
            $DBPass = $resPass['Geslo'];

            $nPassmd5 = md5($nPass);
            //ce je old pass OK in ce sta nova enaka
            if (md5($oPass) == $DBPass and $nPass == $nPassC) {
                //v bazi zamenjamo star password z novim
                $chQuery = "UPDATE PowerUsers SET Geslo = '$nPassmd5' WHERE ID = '$usrID'";
                $res = dbGetResult($chQuery);
                if (!$res) {
                    print( "<p>Could not execute query!</p>");
                    die(mysql_error());
                } else {
                    //ce je geslo uspesno zamenjamo gremo nazaj na my account in povemo da smo zamenjali geslo
                    ////Smo ze na domaci strani
                    //header("Location: ./prodajalecSite.php");
                }
            } else {
                //povemo da nemoremo zamenjati gesla
                echo "<script>";
                echo "alert('Could not change password.');";
                echo "</script>";
            }
        }
    }
}

function login() {  //funkcija za prijavo stranke
    if (isset($_POST["loginUsername"]) and isset($_POST["loginPassword"])) {
        if ($_POST["loginUsername"] != "" and $_POST["loginPassword"] != "") {
            $uName = dbCleanParameter($_POST["loginUsername"]);
            $pass = dbCleanParameter($_POST["loginPassword"]);
            
            // pas damo v md5
            $passmd5 = md5($pass);
            $boolPrijava = false;

            $query = "SELECT * FROM Customers WHERE Email = '$uName' and Geslo = '$passmd5'";
            $result = dbGetResult($query);

            while ($row = mysql_fetch_assoc($result)) { //preveri, ce so vnosi pravilni
                $boolPrijava = true;
                //Pogledamo če je aktiviran račun uporabnika
                if ($row['Aktiviran']==0){
                    echo "<script>";
                    echo "alert('Username not activated, contact administrator!');";
                    echo "</script>";
                    return;
                }
                $uporabnikSeja = $row['ID'];
            }

            if ($boolPrijava) {
                $_SESSION['uporabnik'] = $uporabnikSeja;
                $_SESSION['uporabnikUname'] = $uName;
                $_SESSION['uporabnikPass'] = $pass;
                $boolCookie = true;
                header("Location: ./prijava.php?call=cookie");
            } else {

                if (isset($_COOKIE["language"])) {
                    if ($_COOKIE["language"] == "slo") {
                        echo "<script>";
                        echo "alert('Nepravilni podatki!');";
                        echo "</script>";
                    } else {
                        echo "<script>";
                        echo "alert('Invalid input!');";
                        echo "</script>";
                    }
                } else {
                    echo "<script>";
                    echo "alert('Invalid input!');";
                    echo "</script>";
                }
            }
        }
    }
}

function sellerLogin() {  //funkcija za prijavo admina
    if (isset($_POST['SellerLoginUsername']) and isset($_POST['SellerLoginPassword'])) {
        if ($_POST['SellerLoginUsername'] != "" and $_POST['SellerLoginPassword'] != "") {

            //PRIJAVA S CERTIFIKATOM!
            //zaenkrat mam samo prijavo z bazo
            $uName = $_POST["SellerLoginUsername"]; //username je ImePriimek
            $pass = dbCleanParameter($_POST["SellerLoginPassword"]);

            //vpisan pass damo v md5
            $passmd5 = md5($pass);
            
            //locmo username na ime in priimek
            $strings = NULL;
            preg_match_all('/[A-Z][^A-Z]*/', $uName, $strings);
            $name = dbCleanParameter($strings[0][0]);
            $sname = dbCleanParameter($strings[0][1]);
            $boolPrijava = false;
            //pogledamo v bazo
            $query = "SELECT * FROM PowerUsers WHERE Ime = '$name' and Priimek = '$sname' and Geslo = '$passmd5' and Admin = 0";
            $result = dbGetResult($query);
            //preverimo pravilnost vnosov
            while ($row = mysql_fetch_assoc($result)) {
                $boolPrijava = true;
                //Pogledamo če je aktiviran račun prodajalca
                if ($row['Aktiviran']==0){
                    echo "<script>";
                    echo "alert('Username not activated, contact administrator!');";
                    echo "</script>";
                    return;
                }
                    
                $adminSeja = $row['ID'];
            }

            if ($boolPrijava) {
                $_SESSION['seller'] = $adminSeja;
                $_SESSION['sellerUname'] = $uName;
                $_SESSION['sellerPass'] = $pass;
                $boolCookie = true;
                header("Location: ./prodajalecSite.php");
            } else {
                if (isset($_COOKIE["language"])) {
                    if ($_COOKIE["language"] == "slo") {
                        echo "<script>";
                        echo "alert('Bad data!');";
                        echo "</script>";
                    } else {
                        echo "<script>";
                        echo "alert('Invalid input!');";
                        echo "</script>";
                    }
                } else {
                    echo "<script>";
                    echo "alert('Invalid input!');";
                    echo "</script>";
                }
            }
        }
    }
}

function adminLogin() {  //funkcija za prijavo admina
    if (isset($_POST['AdminLoginUsername']) and isset($_POST['AdminLoginPassword'])) {
        if ($_POST['AdminLoginUsername'] != "" and $_POST['AdminLoginPassword'] != "") {

            //PRIJAVA S CERTIFIKATOM!
            //zaenkrat mam samo prijavo z bazo
            $uName = dbCleanParameter($_POST["AdminLoginUsername"]); //username je ImePriimek
            $pass = dbCleanParameter($_POST["AdminLoginPassword"]);

            //locmo username na ime in priimek
            $strings = NULL;
            preg_match_all('/[A-Z][^A-Z]*/', $uName, $strings);
            $name = dbCleanParameter($strings[0][0]);
            $sname = dbCleanParameter($strings[0][1]);
            $boolPrijava = false;

            //pogledamo v bazo
            $query = "SELECT * FROM PowerUsers WHERE Ime = '$name' and Priimek = '$sname' and Geslo = '$pass' and Admin = 1";
            $result = dbGetResult($query);

            //preverimo pravilnost vnosov
            while ($row = mysql_fetch_assoc($result)) {
                $boolPrijava = true;
                $adminSeja = $row['ID'];
            }

            if ($boolPrijava) {
                $_SESSION['admin'] = $adminSeja;
                $_SESSION['adminUname'] = $uName;
                $_SESSION['adminPass'] = $pass;
                $boolCookie = true;
                header("Location: ./adminSite.php");
            } else {
                if (isset($_COOKIE["language"])) {
                    if ($_COOKIE["language"] == "slo") {
                        echo "<script>";
                        echo "alert('Nepravilni podatki!');";
                        echo "</script>";
                    } else {
                        echo "<script>";
                        echo "alert('Invalid input!');";
                        echo "</script>";
                    }
                } else {
                    echo "<script>";
                    echo "alert('Invalid input!');";
                    echo "</script>";
                }
            }
        }
    }
}

function redirectToAdmLogin() {
    if (!isset($_SESSION['admin']))
        header("Location: ./adminPrijava.php");
    if (isset($_GET["call"]) && $_GET["call"] == "logout") {
        $_SESSION["admin"] = null;
        header("Location: ./adminPrijava.php");
    }
}

function redirectToSellerLogin() {
    if (!isset($_SESSION['seller']))
        header("Location: ./prodajalecPrijava.php");
    if (isset($_GET["call"]) && $_GET["call"] == "logout") {
        $_SESSION["seller"] = null;
        header("Location: ./prodajalecPrijava.php");
    }
}

function language($loc) { //piskoti, ki si zapomnijo jezik
    if (isset($_GET["lang"])) {
        $lang = $_GET["lang"];
        define("ONE_HOUR", 60 * 60);
        setcookie("language", "$lang", time() + ONE_HOUR);
        header("Location: ./$loc");
    }

    if (isset($_COOKIE["language"])) {
        $language = $_COOKIE["language"];
        echo "<input id=\"lang\" style=\"display: none;\" value=\"$language\">";
        echo "<input id=\"lctn\" style=\"display: none;\" value=\"$loc\">";
    } else {
        echo "<input id=\"lang\" style=\"display: none;\" value=\"eng\">";
        echo "<input id=\"lctn\" style=\"display: none;\" value=\"$loc\">";
    }
}

function inclHeader() { //funkcija, ki se klice na zacetku vsake strani.
    session_start();
    $index = strrpos($_SERVER["PHP_SELF"], "/");
    language(substr($_SERVER["PHP_SELF"], $index + 1));
}

function footer() {
    ?><div id="footer">
        Copyright © Podutik Records
        <br/>
        Powered by Delo and Volja
    </div><?php
}

function updateOrdersAtSalesman($id) {
    $cartString = dbCleanParameter(join(',', $_SESSION['cart']));
    $_SESSION['cart'] = null;
    $datum = date("Y-m-d H:i:s");
    $query = "INSERT INTO Narocilo (narocnik, status, artikli, datum)" .
            " VALUES ('$id','0','$cartString', '$datum')";
    if (!( $result = dbGetResult($query) )) {
        print( "<p>Could not execute query!</p>");
        die(mysql_error() . "</body></html>");
    } else {
        return TRUE;
    }
}

function updateCart($query, $idU) {  //funkcija, ki shrani artikle v ko�aro
    if (isset($_GET["call"])) {
        if ($_GET["call"] == "order") {

            $oldCart = dbGetResult($query);
            $row = mysql_fetch_assoc($oldCart);
            $oldC = $row['cart'];
            $cartString = "";
            foreach ($_SESSION['cart'] as $value) {
                $cartString .= $value . ",";
            }

            $ol = explode(",", $oldC);
            $nw = explode(",", $cartString);

            for ($k = 0; $k < count($ol) - 1; $k++) {
                for ($r = 0; $r < count($nw) - 1; $r++) {
                    if ($r >= count($nw) - 1)
                        break;
                    if ($ol[$k] == $nw[$r]) {
                        $nw[$r] = -1;
                    }
                }
            }

            $ns = "";
            for ($p = 0; $p < count($nw) - 1; $p++) {
                if ($nw[$p] != -1)
                    $ns.=$nw[$p] . ",";
            }

            $newCart = $oldC . $ns;
            if ($newCart[strlen($newCart) - 1] != ',')
                $newCart .=',';
            $newCart=dbCleanParameter($newCart);
            $idU=dbCleanParameter($idU);
            $queryUpdate = "UPDATE Uporabnik SET cart='$newCart' WHERE id = $idU";

            dbGetResult($queryUpdate);  //klic, ki shrani podatke o ko�ari v bazo
            $_SESSION['cart'] = null;
        }
    }
}

function displayOrders() {   //funkcija, ki prika�e naro�ene artikle
    if (isset($_SESSION['uporabnik']) and isset($_POST['potrdiKosarico'])) {

        $row = join(',', dbCleanParameter($_SESSION['cart']));
        if ($row != "") {
            print "<h6 id=\"receipt\">Your Order</h6>
				   <div id=\"content\">";
            $queryGetProducts = "SELECT slika, izvajalec, album, cena FROM Artikel WHERE id IN ($row)";
            $content = dbGetResult($queryGetProducts);
            $counterOut = 0;
            $totalPrice = 0;
            while ($row = mysql_fetch_assoc($content)) {
                $artist = $row['izvajalec'];
                $album = $row['album'];
                $price = $row['cena'];
                $image = $row['slika'];
                if ($counterOut % 2 != 0) {
                    print "<div class=\"product\">
					<img src=\"$image\" class=\"productpic\"  alt=\"$artist\" />
					<div class=\"description\">
						<h4>$artist</h4><br/>
						<h5>$album</h5>                                               
						<br/>
						<br/>
                                                <h4>$$price</h5>
					</div>
					</div>";
                } else {
                    print "<div class=\"product2\">
					<img src=\"$image\" class=\"productpic\"  alt=\"$artist\"  />
					<div class=\"description\">
						<h4>$artist</h4><br/>
						<h5>$album</h5>                                                
						<br/>
						<br/>
                                                <h4>$$price</h5>
					</div>
					</div>";
                }
                $totalPrice += $price;
                $counterOut += 1;
            }
            $partial = round($totalPrice, 2);
            $ship = round($totalPrice / 10 + 1.99, 2);
            $total = $partial + $ship;

            print "<div class=\"checkout\" style=\"float: left; margin-bottom: 75px; \">
                                    <h1><label id=\"sub\">Subtotal: </label></h1> <h2>$$partial</h2>
                                    <br/>
                                    <h1><label id=\"shp\">Shipping: </label></h1> <h2>$$ship</h2>
                                    <br/>
                                    <hr/>
                                    <h1><label id=\"tot\">Total: </label></h1> <h2>$$total</h2>
                               </div>";

            print "<form method=\"post\" action=\"vsaNarocila.php\">
                                    <input type=\"number\" name=\"potrdi\" value=\"1\" style=\"visibility: hidden;\" />
                                    <input type=\"image\" src=\"ok.jpg\" id=\"ok\" style=\" clear: right; margin: 50px; margin-top: 70px; margin-right: 170px;\" class=\"checkout\"  alt=\"Ok\" />
                               </form>
                               </div>";
        } else {
            print "<h6 id=\"noOrders\">You have no orders</h6>
				   <div id=\"content\" style=\"height: 200px\" >
				   </div>";
        }

        return $totalPrice;
    } else {
        print "<h6 id=\"noOrders\">You have no orders</h6>
				   <div id=\"content\" style=\"height: 200px\" >
				   </div>";
    }
}

function displayPreviousOrders() {   //funkcija, ki prika�e naro�ene artikle
    if (isset($_SESSION['uporabnik'])) {
        $idU = dbCleanParameter($_SESSION['uporabnik']);
        $query[0] = "SELECT * FROM Narocilo WHERE narocnik = $idU and status = 0";
        $query[1] = "SELECT * FROM Narocilo WHERE narocnik = $idU and status = 1";
        $query[2] = "SELECT * FROM Narocilo WHERE narocnik = $idU and status = 2";
        print "<h6 >Your Previous Orders</h6>
                    <div id=\"content\">";
        for ($index = 0; $index < count($query); $index++) {
            if (($result = dbGetResult($query[$index]))) {
                echo "<div style=\"margin: 5px\";>";
                $boolProcess = True;
                while ($orderType = mysql_fetch_assoc($result)) {

                    if ($boolProcess) {
                        if ($index == 0) {
                            echo "<h3 class=\"ordrs\">Not Processed</h3>";
                        } else if ($index == 1) {
                            echo "<h3 class=\"ordrs\">Approved</h3>";
                        } else {
                            echo "<h3 class=\"ordrs\">Not Approved</h3>";
                        }
                    }
                    $boolProcess = False;

                    echo "<div id=\"previous\"style=\"clear: both; margin-left: 20px;\">";

                    $cart = dbCleanParameter($orderType['artikli']);
                    $datum = split(' ', $orderType['datum']);
                    $datumDate = split('-', $datum[0]);
                    $datumUra = split(':', $datum[1]);
                    $queryArtikli = "SELECT * FROM Artikel WHERE id IN ($cart)";
                    $resultArtikli = dbGetResult($queryArtikli);
                    print "<h4>Ordered on $datumDate[2]. $datumDate[1]. $datumDate[0] $datumUra[0]:$datumUra[1]</h4>";
                    $cena = 0;
                    while ($artikel = mysql_fetch_assoc($resultArtikli)) {
                        $izv = $artikel['izvajalec'];
                        $alb = $artikel['album'];
                        print "$izv: $alb<br/>";
                        $cena += $artikel['cena'];
                    }
                    echo "<h5>Total price: $$cena<h5>";
                    echo "<br/><br/>";
                    echo "</div>";
                }
                echo "</div>";
            }
        }
        print "</div>";
    } else {
        print "<h6 id=\"noOrders\">You have no orders</h6>
				   <div id=\"content\" style=\"height: 200px\" >
				   </div>";
    }
}

function displaySellerOrders() {   //funkcija, ki prika�e naro�ene artikle
    //if (isset($_SESSION['uporabnik'])){
    $query = "SELECT * FROM Narocilo WHERE status = 0 or status = 1 ORDER BY status";

    print "<h6>New Orders</h6>
                    <div id=\"content\">";
    if (($result = dbGetResult($query))) {
        echo "<div style=\"margin: 0px\";>";
        while ($order = mysql_fetch_assoc($result)) {

            echo "<div id=\"previous\"style=\"clear: both; margin-left: 0px;\">";

            $buyer = dbCleanParameter($order['narocnik']);
            $queryBuyer = "SELECT ime, priimek FROM Customers WHERE id ='$buyer'";
            $resultBuyer = dbGetResult($queryBuyer);
            $buyerProfile = mysql_fetch_assoc($resultBuyer);
            $ime = $buyerProfile['ime'];
            $priimek = $buyerProfile['priimek'];
            $cart = dbCleanParameter($order['artikli']);
            $datum = split(' ', $order['datum']);
            $datumDate = split('-', $datum[0]);
            $datumUra = split(':', $datum[1]);
            $idO = $order['id'];
            print "<h4>Order ID: $idO</h4>";
            print "<h4>Ordered by $ime $priimek on $datumDate[2]. $datumDate[1]. $datumDate[0] $datumUra[0]:$datumUra[1]</h4>";
            $queryArtikli = "SELECT * FROM Artikel WHERE id IN ($cart)";
            $resultArtikli = dbGetResult($queryArtikli);
            $cena = 0;
            while ($artikel = mysql_fetch_assoc($resultArtikli)) {
                $izv = $artikel['izvajalec'];
                $alb = $artikel['album'];
                print "$izv: $alb<br/>";
                $cena += $artikel['cena'];
            }
            print "<h5>Total price: $$cena<h5>";
            if ($order['status'] == 0) {
                print "<form id=\"form$idO\" method=\"post\" action=\"\">   
                                    <button type=\"submit\" name=\"confirm\" value=\"$idO\">Confirm</button>
                                    <button type=\"submit\" name=\"reject\" value=\"$idO\">Reject</button>                                      
                               </form>";
            } else if ($order['status'] == 1) {
                print "<form id=\"form$idO\" method=\"post\" action=\"\">
                                    <button type=\"submit\" name=\"cancel\" value=\"$idO\">Cancel</button>                                   
                               </form>";
            }
            echo "<br/><br/>";


            //..... dalje
            //POBRISSS LINK DO RACUNA IZ VSEH STRANI!!! DOSTOPN SAMO IZ CHECKOUTA
            echo "</div>";
        }
        echo "</div>";
    }


    print "</div>";
    /* }else{
      print "<h6 id=\"noOrders\">You have no orders</h6>
      <div id=\"content\" style=\"height: 200px\" >
      </div>";
      } */
}

function obdelaj() {
    global $rootLog;
    $boolOk = True;
    $id = 0;

    $log=new Dnevnik();
    $log->lfile($rootLog);
    $user=  getNamePowerUser($_SESSION['seller']);
    
    if (isset($_POST['confirm'])) {
        $id = dbCleanParameter($_POST['confirm']);


        $queryCart = "SELECT artikli FROM Narocilo WHERE id = '$id'";
        $resultCart = dbGetResult($queryCart);
        $cart = mysql_fetch_assoc($resultCart);
        $artikli = dbCleanParameter($cart['artikli']);

        $querySelectZaloga = "SELECT zaloga FROM Artikel WHERE id IN ($artikli)";
        $resultZaloge = dbGetResult($querySelectZaloga);

        while ($zaloge = mysql_fetch_assoc($resultZaloge)) {
            if ($zaloge['zaloga'] < 1)
                $boolOk = False;
        }

        if ($boolOk) {
            $queryUpdateZaloge = "UPDATE Artikel SET zaloga = zaloga - 1 WHERE id IN ($artikli)";
            $resultUpdateZaloge = dbGetResult($queryUpdateZaloge);
            
            $id =  dbCleanParameter($id);
            $query = "UPDATE Narocilo SET status = '1' WHERE id = '$id'";
            $resultArtikli = dbGetResult($query);
            $log->lwrite("[$user] Potrjeno narocilo z id=$id");
            $log->lclose();
        }
    }

    if (isset($_POST['reject'])) {
        $id = dbCleanParameter($_POST['reject']);
        $query = "UPDATE Narocilo SET status = '2' WHERE id = '$id'";
        $resultArtikli = dbGetResult($query);
        $log->lwrite("[$user] Zavrnjeno narocilo z id=$id");
        $log->lclose();
    }

    if (isset($_POST['cancel'])) {
        $id = dbCleanParameter($_POST['cancel']);

        $id =  dbCleanParameter($id);
        $queryCart = "SELECT artikli FROM Narocilo WHERE id = '$id'";
        $resultCart = dbGetResult($queryCart);
        $cart = mysql_fetch_assoc($resultCart);
        $artikli = dbCleanParameter($cart['artikli']);

        $queryUpdateZaloge = "UPDATE Artikel SET zaloga = zaloga + 1 WHERE id IN ($artikli)";
        $resultUpdateZaloge = dbGetResult($queryUpdateZaloge);

        $query = "UPDATE Narocilo SET status = '2' WHERE id = '$id'";
        $resultArtikli = dbGetResult($query);
        $log->lwrite("[$user] Stornirano narocilo z id=$id");
        $log->lclose();
    }

    if (!$boolOk) {

        print "<script>
              alert(\"Not enough items in stock, order will be canceled.\");  
              </script>";

        $query = "UPDATE Narocilo SET status = '2' WHERE id = '$id'";
        $resultArtikli = dbGetResult($query);
    }
        
}

function logout() {  //funkcija za odjavo
    if (isset($_GET["call"])) {
        if ($_GET["call"] == "logout") {
            echo "<script>";
            echo "alert('Uspesno ste se odjavili!');";
            echo "</script>";
            $_SESSION['uporabnik'] = null;
            $_SESSION['admin'] = null;
            $_SESSION['seller'] = null;
            $_SESSION['cart'] = null;
            //header("Location: ./index.php");
        }
    }
}

function initializeCart() {  //funkcija, ki ustvari ko�arico
    if (isset($_GET["call"]) and isset($_SESSION['uporabnik'])) {
        if ($_GET["call"] == "cart") {
            $id_temp = dbCleanParameter($_GET["id"]);
            if (!isset($_SESSION['cart']))
                $_SESSION['cart'] = array();
            if (!in_array("$id_temp", $_SESSION['cart']))
                array_push(dbCleanParameter($_SESSION['cart']), "$id_temp");
        }
    }
}

function showMainNav() {   //funkcija, ki glede na status stranke (prijavljena, neprijavljena) prikaže glavni menu
    global $root;
    if (isset($_SESSION['uporabnik'])) {      //prijavljena je stranka
        print "<div class = \"login\">
                            <strong><a href=\"index.php?call=logout\" id=\"logout\">Logout</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href=\"vsaNarocila.php\" id=\"narocila\">View Orders</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href=\"kosarica.php\" id=\"cart\">View Cart</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href=\"index.php\" id=\"toStore\">To Store</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href=\"customerAccount.php\" id=\"uAcc\">My Account</a></strong>
                    </div>";
    } else if (isset($_SESSION['admin'])) {     //prijavljen je admin
        print "<div class = \"login\">
                            <strong><a href='" . $root . "adm/adminSite.php?call=logout' id=\"logout\">Logout</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href='" . $root . "index.php' id=\"toStore\">To Store</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href='" . $root . "adm/adminSite.php' id=\"aAcc\">Administrator Site</a></strong>
                    </div>";
    } else if (isset($_SESSION['seller'])) {     //prijavljen je seller
        print "<div class = \"login\">
                            <strong><a href=\"" . $root . "index.php?call=logout\" id=\"logout\">Logout</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href=\"" . $root . "index.php\" id=\"toStore\">To Store</a></strong>
                    </div>
                    <div class = \"login\">
                            <strong><a href=\"" . $root . "prodaja/prodajalecSite.php\" id=\"sAcc\">Seller Site</a></strong>
                    </div>";
    } else {
        print "<div class = \"login\">
                        <strong><a href=\"registracija.php\" id=\"regnav\">Register</a></strong>
                </div>
                <div class = \"login\">
                        <strong><a href=\"prijava.php\" id=\"lgnav\">Login</a></strong>
                </div>";
    }
}

function displaySideCart() {   //funkcija, ki prikaže stranski menu ter artikle v košarici
    if (isset($_SESSION['cart']) and isset($_SESSION['uporabnik'])) {
        if (count($_SESSION['cart']) > 0) {
            $dispCart = "";
            foreach ($_SESSION['cart'] as $value) {
                $dispCart .= dbCleanParameter($value) . ",";
            }
            $dispCart = substr($dispCart, 0, -1);
            $query = "SELECT slika FROM Artikel WHERE id IN ($dispCart)";
            $result = dbGetResult($query);

            echo "<h3 id=\"izbrali\" style=\"margin-bottom: 10px;\"> In cart</h3>";
            while ($row = mysql_fetch_assoc($result)) {
                $slika = $row['slika'];
                echo "<img src=\"$slika\" alt=\"slika\" class=\"inCart\"/><br/>";
            }
        }
    }
}

function displayCart() {   //funkcija, ki napolni tabelo na strani ko�arica z vsebino iz ko�are
    $totalPrice = 0;
    $dispCart = "";
    foreach ($_SESSION['cart'] as $value) {
        $dispCart .= dbCleanParameter($value) . ",";
    }
    $dispCart = substr($dispCart, 0, -1);
    $query = "SELECT id, izvajalec, album, cena FROM Artikel WHERE id IN ($dispCart)";
    $result = dbGetResult($query);

    while ($row = mysql_fetch_assoc($result)) {
        $id = $row['id'];
        $izvajalec = $row['izvajalec'];
        $album = $row['album'];
        $cena = $row['cena'];
        $totalPrice += $cena;

        print "<tr>
				<td style=\"padding-left: 10px; height: 31px;\"><a href=\"Kosarica.php?call=delete&id=$id\"><img src=\"trash.gif\" class=\"thrash\" alt=\"Remove item\" /></a></td>
				<td><strong>$izvajalec:</strong> $album</td>
				<td>$$cena</td></tr>";
    }
    return $totalPrice;
}

function novoAlerts() {   //funkcija, ki prika�e opozorila ob nepravilni aktivnosti
    
    if (isset($_GET["call"]) and !isset($_SESSION['uporabnik']) and !isset($_POST['qry'])) {
        if (dbCleanParameter($_GET["call"]) == "cart") {
            
            
            
            if (isset($_COOKIE["language"])) {
                if ($_COOKIE["language"] == "slo") {
                    echo "<script>";
                    echo "alert('Za to storitev morate biti prijavljeni!');";
                    echo "</script>";
                } else {
                    echo "<script>";
                    echo "alert('You must be logged in to use this servise.');";
                    echo "</script>";
                }
            } else {
                echo "<script>";
                echo "alert('You must be logged in to use this servise.');";
                echo "</script>";
            } 
        }
    }
}

function deleteFromCart() {  //funkcija, ki pobri�e artikel iz ko�are
    if (isset($_GET["call"])) {
        if ($_GET["call"] == "delete") {
            $key = $_GET["id"];
            $_SESSION['cart'] = array_diff($_SESSION['cart'], array($key));
        }
    }
}

function setCookies() {   //funkcija, ki nastavi pi�kote ob prijavi
    if (isset($_GET["call"])) {
        if ($_GET["call"] == "cookie") {
            define("ONE_HOUR", 60 * 60); // define constant
            // write each form field�s value to a cookie and set the 
            // cookie�s expiration date
            setcookie("userName", $_SESSION['uporabnikUname'], time() + ONE_HOUR);
            setcookie("password", $_SESSION['uporabnikPass'], time() + ONE_HOUR);
            header("Location: ./index.php");
        }
    }
}

//metoda ki navadno HTTP povezavo spremeni v HTTPS
function requestHTTPS() {
    if ($_SERVER['HTTPS'] != "on") {
        header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
        exit();
    }
}
?>